<?php

class Login extends BaseController{

	public function __construct() {
		parent::__construct();
		$this->load->model('LoginModel');
	}

	public function index() {
		if (isset($_SESSION['user'])) {
			redirect('welcome');
		} else {
			$this->master_view('login',array());
		}
	}


	public function doLogin() {
		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
		if($this->form_validation->run() == false)
		{
			echo $this->generateJasonResponse('fail','fail','');
		} else {
			$passwordFromDB = $this->LoginModel->getPassword($_POST['username']);
			if ($passwordFromDB == null) {
				echo $this->generateJasonResponse('user does not exist','','');
			} else {
				if ($this->validatePassword(($_POST['password']),$passwordFromDB)) {
					$_SESSION['user'] =  $_POST['username'];
					echo $this->generateJasonResponse('','','1');
				} else {
					echo $this->generateJasonResponse('user or password is not correct','','');
				}
			}
		}

	}

	public function doLogout() {
		session_destroy();
		redirect('welcome');
	}

	public function register() {
		$this->master_view('register',array());
	}

	public function doRegister() {
		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
		if($this->form_validation->run() == false)
		{
			echo $this->generateJasonResponse('not a valid username','not a valid password','');
		} else {
			if (!$this->LoginModel->insertUser($_POST['username'], $this->hashClearPassword($_POST['password']))) {
				echo $this->generateJasonResponse('user already exist','','');

			} else {
				$_SESSION['user'] =  $_POST['username'];
				echo $this->generateJasonResponse('','','1');
			}
		}
	}

	// Cleartext to salted hash
	// $clearPassword - the password to hash
	// returns - the hash of the password (128 hex characters)
	function hashClearPassword($clearPassword) {
		// Generate a 256 bit random salt using CSPRNG function
		$greatSalt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));

		// Take our new salt and prepend the password and hash the lot
		$hash = hash("sha256", $greatSalt . $clearPassword);

		// Combine the salt with the hash so you get 128 characters
		$returnValue = $greatSalt . $hash;
		return $returnValue;
	}

	// Check hash
	// return true if hash is the correct for that password
	// $correctHash - the hash stored in our db or created by hashClearPassword()
	// $clearPassword - the password to verify
	// returns - true if the password is valid | false if it isn't
	function validatePassword($clearPassword, $correctHash) {

		// Extract the salt from the string
		$ourSalt = substr($correctHash, 0, 64);

		// Extract the hash from the string
		$validHash = substr($correctHash, 64, 64);

		// Generate a hash for comparison
		$compareHash = hash("sha256", $ourSalt . $clearPassword);
		// Test the validHash against the one from the supplied password
		return $compareHash === $validHash;
	}

	function generateJasonResponse($username,$password,$redirect) {
		$data = array(
                    'username' => $username, 
                    'password' => $password,
					'redirect' => $redirect
		);
			
		return  json_encode($data);

	}
}

?>